<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-12-27 10:03:28
 * @LastEditors: 李天惊 uf_lee@163.com
 * @LastEditTime: 2023-01-05 12:00:07
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\Quarantine\components\Edit.vue
 * Copyright (c) 2022 by 李天惊 uf_lee@163.com, All Rights Reserved. 
 * 检验检疫记录单-修改
-->
<script setup lang="ts">
import { onUnmounted, reactive, ref, unref } from 'vue'
import { ElButton, ElDatePicker, ElInput, ElSelectV2 } from 'element-plus'

import { ContentWrap } from '@/components/ContentWrap'
import { Form } from '@/components/Form'
import { Table } from '@/components/Table'
import { Dialog } from '@/components/Dialog'
import { UploadMultiple } from '@/components/UploadMultiple'

import EarconRefer from './EarconRefer.vue'

import { useForm } from '@/hooks/web/useForm'
import { useIcon } from '@/hooks/web/useIcon'

import { required } from '@/utils/formRules'

import { adminFaUserListApi } from '@/api/fa/user'
import { adminFaQuarantineOrderSeeApi } from '@/api/fa/quarantine'
import { adminFaEarconListApi } from '@/api/fa/earcon'
import { adminFaPastureListApi } from '@/api/fa/pasture'
import { sysDictRelsApi } from '@/api/dict'

// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
/****************************** 变量 start ******************************/
const dict: any = wsCache.get('dict')
const data = ref<any>({})
const dictRelsData = ref() // 联动数据
const breedSubData = ref([]) // 品种的枚举
const iconAdd = useIcon({ icon: 'material-symbols:add' })
const iconDel = useIcon({ icon: 'material-symbols:delete-outline' })
const iconFile = useIcon({ icon: 'ic:outline-file-present' })

const fileRef = ref()
const dFileRef = ref()
const d_row = ref<any>({})
const actionType = ref('')
const saveLoading = ref(false)
const d_id = ref(0) //主要用来给每个行添加一个序号，删除的时候好定位

const dialogVisible = ref(false)
const dialogTitle = ref('')

const rules = reactive({
  customer_id: [required],
  creation_user_id: [required],
  breed: [required],
  breed_sub: [required],
  type: [required],
  state: [required]
})

const dFile = ref([])
/****************************** 变量 end ******************************/

/****************************** 组件参数 start ******************************/
// 获取参数
const props = defineProps({
  id: {
    type: String,
    default: null
  }
})
/****************************** 组件参数 end ******************************/

const changeDId = async (data) => {
  if (data.detailedData.length > 0) {
    const newData = data
    for (let i = 0; i < newData.detailedData.length; i++) {
      d_id.value++
      newData.detailedData[i].d_id = d_id.value
    }
    return newData
  } else {
    return data
  }
}

// 调用查看接口获取信息
const getQuarantineOrderSee = async () => {
  if (props.id) {
    const res = await adminFaQuarantineOrderSeeApi({ id: props.id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      data.value = await changeDId(res.data)
      // 明细信息处理一下，加上d_id
      await methods.setValues(data.value)
    }
  } else {
    data.value.state = '1'
    data.value.detailedData = []
    data.value.fileData = []
    await methods.setValues(data.value)
  }
}

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

// 选择畜别的时候触发，处理品种类容
const breedChange = async (value) => {
  await breedGetSub(value)
  let formData = await methods.getFormData()
  await methods.setValues({ ...formData, breed_sub: '' })
}

const onCustomer = async () => {
  data.value.detailedData = []
}

const schema: any = [
  {
    field: 'customer_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: adminFaPastureListApi,
      response: { count: 'count', data: 'data' },
      title: '选择创建人（双击选择）',
      nameField: 'customer_name',
      relNameField: 'name',
      valueField: 'id',
      crudSchemas: [
        { field: 'name', label: '牧场名称', search: { show: true } },
        { field: 'code', label: '牧场编码', search: { show: true } }
      ],
      modelName: data.value.customer_name,
      onChange: onCustomer
    }
  },
  {
    field: 'breed',
    label: '畜别',
    component: 'Select',
    componentProps: {
      options: dict.breed,
      onChange: breedChange
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    component: 'Select',
    componentProps: {
      options: breedSubData
    }
  },
  // { component: 'InputNumber', field: 'number', label: '牲畜数量' },
  // { component: 'InputNumber', field: 'quarantine_number', label: '检验数量' },
  {
    field: 'type',
    label: '类型',
    component: 'Select',
    componentProps: {
      options: dict.quarantine_order_type
    }
  },
  {
    field: 'state',
    label: '状态',
    component: 'Select',
    componentProps: {
      options: dict.quarantine_order_state
    }
  },
  {
    field: 'creation_user_id',
    label: '创建人',
    component: 'DialogRefer',
    componentProps: {
      getListApi: adminFaUserListApi,
      response: { count: 'count', data: 'data' },
      title: '选择创建人（双击选择）',
      nameField: 'creation_user_name',
      relNameField: 'nickname',
      valueField: 'id',
      crudSchemas: [
        { field: 'nickname', label: '姓名', search: { show: true } },
        { field: 'username', label: '用户名', search: { show: true } },
        { field: 'source', label: '类型' }
      ],
      modelName: data.value.creation_user_name
    }
  }
]
const { register, methods, elFormRef } = useForm({
  schema: schema
})

const getFormData = async () => {
  let formData = await methods.getFormData()
  // const sku = unref(skuRef)
  // let skuData = sku?.getData()
  const file = unref(fileRef) //附件
  let fileData = file?.getData()
  // const goodsDetails = unref(goodsDetailsRef) //明细
  // let goods_details = goodsDetails?.getData()
  // let goods_tag = getGoodsTag()
  // let goods_details = data.value.goods_details
  // let goods_carousel = data.value.goods_carousel
  return { ...formData, fileData: fileData, detailedData: data.value.detailedData }
}

const getEarconListApi = async (new_data) => {
  let formData: any = await methods.getFormData()
  if (!formData.customer_id) {
    return { code: 500, count: 0, msg: '不能没有customer_id' }
  }
  // console.log('formData', !formData.customer_id, new_data, adminFaEarconListApi)
  const res = await adminFaEarconListApi({ ...new_data, customer_id: formData.customer_id })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    return res
  }
}

defineExpose({
  elFormRef,
  getFormData
})
onUnmounted(async () => {
  console.log(await getFormData(), '6666')
})
/****************************** 明细配置 start ******************************/
const d_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 30
  },
  // {
  //   field: 'd_id',
  //   label: 'd_id',
  //   width: 150
  // },
  {
    field: 'earcon_id',
    label: '资产编码',
    width: 150
  },
  {
    field: 'state',
    label: '状态',
    width: 150
  },
  {
    field: 'note',
    label: '备注',
    width: 150
  },
  // {
  //   field: 'creation_time',
  //   label: '创建时间',
  //   width: 180
  // },
  {
    field: 'action',
    width: 120,
    fixed: 'right',
    label: '操作'
  }
])

/****************************** 明细配置 end ******************************/

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'add_d':
      d_id.value++
      data.value.detailedData.push({ d_id: d_id.value, state: '1' })
      break
    case 'del_d':
      let row_i = data.value.detailedData.findIndex((item) => {
        return item.d_id == row.d_id
      })
      data.value.detailedData.splice(row_i, 1)
      console.log(row, 'row')

      break
    case 'file_d':
      dialogTitle.value = '附件'
      d_row.value = row
      if (row.file) {
        dFile.value = JSON.parse(row.file)
      } else {
        dFile.value = []
      }
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}

const saveFile_d = async () => {
  saveLoading.value = true
  const dFile = unref(dFileRef)
  let row_i = data.value.detailedData.findIndex((item) => {
    return item.d_id == d_row.value.d_id
  })
  data.value.detailedData[row_i].file = JSON.stringify(dFile.getData())
  dialogVisible.value = false
  saveLoading.value = false
}

/****************************** 初始化 start ******************************/
const init = async () => {
  // 获取关联关系
  await getDictRels()
  // 调用查看接口查询数据
  await getQuarantineOrderSee()
  // 跟新畜别
  if (data.value.breed) {
    await breedGetSub(data.value.breed)
  }
}
init()
/****************************** 初始化 end ******************************/
</script>
<template>
  <div>
    <ContentWrap title="主数据">
      <Form :rules="rules" @register="register" :data="data" />
    </ContentWrap>
    <ContentWrap title="附件">
      <UploadMultiple
        ref="fileRef"
        v-model="data.fileData"
        :response="{
          url: 'file_url',
          name: 'file_name',
          file_type: 'file_type'
        }"
      />
    </ContentWrap>
    <ContentWrap title="明细数据">
      <div class="mb-10px">
        <!-- <ElButton type="primary">新增行</ElButton> -->
        <ElButton circle :icon="iconAdd" @click="action('add_d')" title="新增行" />
      </div>
      <Table :columns="d_columns" :data="data.detailedData" :selection="false" :border="true">
        <template #earcon_id="{ row }">
          <EarconRefer
            v-model="row.earcon_id"
            :getListApi="getEarconListApi"
            :response="{ count: 'count', data: 'data' }"
            title="选择资产（双击选择）"
            nameField="earcon_code"
            relNameField="code"
            valueField="id"
            :crudSchemas="[
              { field: 'is_selected', label: '是否已选', search: { show: false }, width: 80 },
              { field: 'code', label: '资产编码', search: { show: true } },
              { field: 'film_code', label: '耳标号', search: { show: true } }
            ]"
            :modelName="row.earcon_code"
            :selected="data.detailedData"
          />
        </template>

        <template #note="{ row }">
          <ElInput v-model="row.note" />
        </template>

        <template #state="{ row }">
          <ElSelectV2 v-model="row.state" :options="dict.quarantine_order_detailed_state" />
        </template>

        <template #creation_time="{ row }">
          <ElDatePicker v-model="row.creation_time" style="width: 150px" valueFormat="YYYY-MM-DD" />
        </template>

        <template #action="{ row }">
          <ElButton circle :icon="iconFile" @click="action('file_d', row)" title="附件" />
          <ElButton circle :icon="iconDel" @click="action('del_d', row)" title="删除行" />
        </template>
      </Table>
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <div>
        <UploadMultiple
          ref="dFileRef"
          v-model="dFile"
          :response="{
            url: 'file_url',
            name: 'file_name',
            file_type: 'file_type'
          }"
        />
      </div>

      <template #footer>
        <ElButton type="primary" :loading="saveLoading" @click="saveFile_d()"> 保存 </ElButton>
        <ElButton @click="dialogVisible = false">关闭</ElButton>
      </template>
    </Dialog>
  </div>
</template>
